package com.xch.sboot.service.common;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @author xch
 * 2022/12/30 15:22
 */
@Service
@Slf4j
public class FileService {

    @Value("${file.path}")
    private String rootPath;

    /**
     * 保存文件到本地
     * @param bufferedInputStream 文件输入流
     * @param fileName 文件名 不带尾缀
     */
    public void saveFile(BufferedInputStream bufferedInputStream, String fileName){
        //根据文件保存地址，创建文件输出流
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(rootPath + File.separatorChar + fileName + ".jpg");
            IoUtil.copy(bufferedInputStream, fileOutputStream);
        } catch (Exception e) {
            log.error("saveFile error:{}", e.getMessage());
        } finally {
            try {
                fileOutputStream.close();
                bufferedInputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
